$.namespace("goods.goodsIntroduction.main");

goods.goodsIntroduction.main.g$mainGrid = null;
goods.goodsIntroduction.main.w$editWin = null;

goods.goodsIntroduction.main.goodsTypeData = null;
//显示记录数
var PAGE_SHOW_RECORD_CNT = 8;
// 默认第一页
var PAGE_NUM_INIT = 1;

var pk_goods_id;

/**
 * 主画面初始化操作
 */
goods.goodsIntroduction.main.init = function() {
	goods.goodsIntroduction.main.g$mainGrid = $('#mainGrid');
	goods.goodsIntroduction.main.w$editWin = $('#goodsIntroductionEditWin');
	
	// Modal 窗口关闭时清空所有数据
	$("#goodsDetailModal").on("hidden.bs.modal", function() {
	    $("#mode").val();
	    $("#goodId").val();
	    $("#typeId").val();
		$("#goodId").val("");
		$("input:radio[name=goodsTypeRadio]").attr("checked",false);  
		$("#goodName").val("");
		$("#goodAbbrName").val("");
		$("#goodIntroduce").val("");
		$("#goodSpecs").val("");
		$("#goodPrice").val("");
		$("#goodPriceJp").val("");
		$("#QRCode").attr('src',"images/noPic.jpg");
		$("#imageFiles").fileinput("clear");
	});
	
	$.when($.ajax({
			type : 'post',
			url : $.ctx + '/goods/goodsIntroduction/getGoodsTypeAll',
			success : function(result) {
				 if (result.isSuccess && result.rslt_flag == "0") {
					 var selectHtml = "";
					 $.each(result.data, function(index, res) {
						 selectHtml += '<option value="' + res.typeId + '">' + res.typeName + '</option>';
					 });
					 $("#goods_type_name").append(selectHtml);
					 goods.goodsIntroduction.main.goodsTypeData = result.data;
				 }
			     
				 $('#goods_type_name').selectpicker({
			        liveSearch: true,
			        maxOptions: 1
			     });
			}
		})).done(function(){ goods.goodsIntroduction.main.search();}).fail(function(){ alert("出错啦！"); });
};

/**
 * 商品详情一览检索
 */
goods.goodsIntroduction.main.search = function() {
	
	var typeID = "";
	if ($("#goods_type_name").val() == null || $("#goods_type_name").val() == "") {
		typeID = "";
	} else {
		typeID = $("#goods_type_name").val()[0];
	}
	// 检索条件
	var params = {
		page		: PAGE_NUM_INIT,
		rows		: PAGE_SHOW_RECORD_CNT,
		typeId		: typeID,
		goodName	: $.trim($("#goods_name").val())
	};
	
	$.ajax({
		type : 'post',
		url : $.ctx + '/goods/goodsIntroduction/search',
		data: params,
		success : function(result) {
			 if (result.isSuccess && result.rslt_flag == "0") {
				 // 列表数据绑定
				 goods.goodsIntroduction.main.appendGoodsItem(result);
				
				// 分页部设定
				var pageCount = 0;
				// 检索为0件， 则不显示分页栏
				if(result.data.totalRecord > 0) {
					pageCount = Math.ceil(result.data.totalRecord / PAGE_SHOW_RECORD_CNT); // 取到pageCount的值(把返回数据转成object类型)
				}
				var count = 0;
				if (pageCount <= 5) {
					count = 1;
				} else if (pageCount % 5 == 0) {
					count = pageCount / 5;
				} else {
					count = parseInt(pageCount / 5) + 1;
				}
				
				var currentPage = result.data.pageNo; // 得到urrentPage
				var options = {
		            bootstrapMajorVersion: 3, // 版本
		            currentPage: currentPage, // 当前页数
		            totalPages: pageCount, // 总页数
		            alignment:"right",
		            numberOfPages:5,
		            shouldShowPage: function (type, page, current) {
		            	return true;
		            },
		            itemTexts: function (type, page, current) {
		                switch (type) {
		                  case "first":
		                    return "首页";
		                  case "prev":
		                    return "＜";
		                  case "next":
		                    return "＞";
		                  case "last":
		                    return "尾页";
		                  case "page":
		                    return page;
		                }
		            },
		            itemContainerClass: function (type, page, current) {
		            	if (type == "next" && count != 1 && page <= 5*(count-1)+1 && page != current) {
		            		$('#page').append("<li class='slh'><a>...</a></li>");
		            	}
		            	switch (type) {
						case "first":
						case "prev":
							return (current == 1) ? "hiddenPageBtn" : "pointer-cursor";
						case "next":
						case "last":
							return (current == pageCount) ? "hiddenPageBtn" : "pointer-cursor";
						default:
							return (page == current) ? "active" : "pointer-cursor";
					}
	            },// 点击事件，用于通过Ajax来刷新整个list列表
	            onPageClicked: function (event, originalEvent, type, page) {
		              var typeID = "";
		              if ($("#goods_type_name").val() == null || $("#goods_type_name").val() == "") {
		            		typeID = "";
		              } else {
		            		typeID = $("#goods_type_name").val()[0];
		              }
		              var pageClickParams = {
		            		 rows		: PAGE_SHOW_RECORD_CNT
        		  			,page		: page
        		  			,typeId		: typeID
        		  			,goodName	: $.trim($("#goods_name").val())
		              		};
		              $.ajax({
		            	  url : $.ctx + '/goods/goodsIntroduction/search',
		                  type: "Post",
		                  data: pageClickParams,
		                  success: function (itemData) {
		                      if (result.isSuccess && result.rslt_flag == "0") {
				                  goods.goodsIntroduction.main.appendGoodsItem(result);
		                      }
		                   }
		             });
	               }
	            }
			   // 一览部有数据的情况下
			   if(result.data.results.length > 0) {
				  $('#page').bootstrapPaginator(options);
				  $('#page').css("display", "");
				  $('.sm_ym_total').removeClass("hidden");
				  $('.totalRecords').html(" " + result.data.totalRecord + " ");
			   } else {
				  $('#page').css("display", "none");
				  $('.sm_ym_total').addClass("hidden");
				  
				  $('#list').append("<li class='total'>没有相关记录！</li>");
			   }
		   }
	    }
    });
}

/**
 * 加载商品列表
 */
goods.goodsIntroduction.main.appendGoodsItem = function(result) {
	 var appendContent = "";
	 // 清空一览部数据
	 $("#list").empty();
		
	 // 遍历返回的json
	 $.each(result.data.results, function (index, item) {
		 appendContent += '<div class="col-md-3 col-sm-3 mb" onclick="goods.goodsIntroduction.main.chooseGoodInfo(this);" ondblclick="goods.goodsIntroduction.main.edit(' +item.goodId + ')">';
		 appendContent += '<div class="checked_img" style="position:absolute;left:18px; top:2px; visibility:hidden;"><span style="font-size:20px;color:#FFF;" class="glyphicon glyphicon-ok-circle"></span></div>'
		 appendContent += '<div class="white-panel pn">';
		 appendContent += '    <div class="goods_panel">' + item.goodName+ '</div>';
	     appendContent += '	   <div>';
	     appendContent += '        <input type="hidden" id="goods_id" value="' + item.goodId + '" />';
	     if (item.goodImage == "" || item.goodImage == null) {
	    	 appendContent += '	       <img src="images/noPic.jpg" style="width:98%;height:195px;">';
	     } else {
	    	 appendContent += '			<img src="' + $.ctx + item.goodImage + '" style="width:98%;height:195px;">';
	     }
	     appendContent += '			    <ul class="tm-ind-panel">';
	     appendContent += '			        <li class="tm-ind-item tm-ind-sellCount" data-label="价格">';
	     appendContent += '					    <div class="tm-indcon">';
    	 appendContent += '						    <a href="javascript:;"><span class="tm-label">价格：</span><span';
		 appendContent += '							    class="tm-count">' + item.goodPrice + ' 元</span></a>';
		 appendContent += '					    </div>';
		 appendContent += '			       </li>';
		 appendContent += '			       <li class="tm-ind-item tm-ind-emPointCount" data-spm="库存">';
		 appendContent += '			            <div class="tm-indcon">';
		 appendContent += '					        <a href="javascript:;"><span class="tm-label">库存：</span><span';
		 appendContent += '							    class="tm-count"> '+ item.quantity +' 件</span></a>';
		 appendContent += '				        </div>';
		 appendContent += '			       </li>';
		 appendContent += '			    </ul>';
		 appendContent += '		  </div>';
		 appendContent += '		</div>';
		 appendContent += '	</div>';
         $("#list").append(appendContent);
         appendContent = "";
	 });
};

/**
 * 选择商品
 */
goods.goodsIntroduction.main.chooseGoodInfo = function(event) {
	if($(event).find("div").first().css("visibility")!="hidden"){
		$(event).find("div").first().css("visibility", "hidden");
		$(event).children("div").next().css("box-shadow", "");
	} else {
		$(event).find("div").first().css("visibility", "visible");
		$(event).children("div").next().css("box-shadow", "2px 3px 2px rgba(0, 0, 0, 0.3)");
	}
}

/**
 * 点击添加按钮新增
 */
goods.goodsIntroduction.main.add = function() {
	$(".modal-title").html("新增 ---【商品基本信息】");
	setGoodsDetailModalProperty("0",null);
};

/**
 * 点击更新按钮
 */
goods.goodsIntroduction.main.edit = function(goodId){
	var cnt = 0;
	$.each($(".checked_img"), function(index, item) {
		if ($(item).css("visibility") != "hidden") {
			goodId = $(item).next().find("#goods_id").val();
			cnt ++;
		}
	});
	
	if (cnt > 1) {
		$.alert({
		    title: '提示',
		    content: '请只选择一条记录进行编辑!',
		    text: "确认"
		});
		return;
	}
	
	$(".modal-title").html("更新 ---【商品基本信息】");
	setGoodsDetailModalProperty("1", goodId);
};

/**
 * 商品详情页面属性设定
 */
setGoodsDetailModalProperty = function(mode, goodId) {
	$('.modal-dialog').width(750);
	$('#goodsDetailModal').modal('show');
	$("#goodsDetailModal").draggable({cursor: "move", handle:"div.modal-header", scroll:true});
	// 加载商品分类
	if (goods.goodsIntroduction.main.goodsTypeData != null) {
		$("#goods_type").html("");
		typeHtml = '<ul class="dowebok">';
		$.each(goods.goodsIntroduction.main.goodsTypeData, function(index, res) {
			 typeHtml += '<li><input type="radio" name="goodsTypeRadio" value = "' + res.typeId + '"data-labelauty="' + res.typeName + '"></li>';
		});
		typeHtml += '</ul>';
		$("#goods_type").append(typeHtml);
		$(':input[name=goodsTypeRadio]').labelauty();
	}
	var imageArray = [];
	// 更新的场合
	if (mode == "1") {
		$.ajax({
			type	: "POST",
			dataType: "json",
			data	: {
				"goodId" :goodId
			},
			url : $.ctx + '/goods/goodsIntroduction/findGoodsInfoById',
			success : function(result) {  
				 if (result.isSuccess && result.rslt_flag == "0") {
					$("#goodId").val(result.data.goodId);
					$("input:radio[name=goodsTypeRadio][value=" + result.data.typeId + "]").attr("checked",true);  
		  			$("#goodName").val(result.data.goodName);
		  			$("#goodAbbrName").val(result.data.goodAbbrName);
		  			$("#goodIntroduce").val(result.data.goodIntroduce);
		  			$("#goodSpecs").val(result.data.goodSpecs);
		  			$("#goodPrice").val(result.data.goodPrice);
		  			$("#goodPriceJp").val(result.data.goodPriceJp);
		  			if(result.data.goodQrcodeImageUrl != null && result.data.goodQrcodeImageUrl != "") {
		  				$("#QRCode").attr('src',$.ctx + result.data.goodQrcodeImageUrl); 
		  			}
		  			// 商品图片1
		  			if(result.data.goodImage != null && result.data.goodImage != "") {
		  				imageArray.push($.ctx  + result.data.goodImage);
		  			}
		  			// 商品图片2
		  			if(result.data.goodImage1 != null && result.data.goodImage1 != "") {
		  				imageArray.push($.ctx + result.data.goodImage1);
		  			}
		  			// 商品图片3
		  			if(result.data.goodImage2 != null && result.data.goodImage2 != "") {
		  				imageArray.push($.ctx + result.data.goodImage2);
		  			}
		  			
		  			// 文件上传初始化
		  			$("#imageFiles").fileinput({
		  			    language		: 'zh',							// 中文  
		  			    uploadUrl		: $.ctx + '/goods/goodsIntroduction/addGoodsPictures',
		  			    deleteUrl		: $.ctx + '/goods/goodsIntroduction/delPictures',
		  			    showPreview		: true,              			// 展前预览  
		  			    showUpload		: false,              			// 不显示上传按钮  
		  			    showCaption		: false,             			// 不显示文字表述  
		  			    uploadAsync		: false,                         // 采用同步上传  
		  			    removeFromPreviewOnError:true,                 	// 当文件不符合规则，就不显示预览  
		  			    maxFileCount	: 3,							// 最大上传图片数
		  			    maxFileSize		: 512,                          // 单位为kb，如果为0表示不限制文件大小  
		  			    browseClass 	: "btn btn-info",
		  			    allowedFileExtensions: ["jpg", "jpeg", "gif", "png","bmp"],
		  			    initialPreview	: imageArray,
		  			    initialPreviewFileType : 'image',
		  			    initialPreviewAsData: true,
		  		        previewFileIconSettings: {  
		  		            'docx': '<i class="fa fa-file-word-o text-primary"></i>',  
		  		            'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',  
		  		            'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',  
		  		            'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',  
		  		            'zip': '<i class="fa fa-file-archive-o text-muted"></i>',  
		  		            'sql': '<i class="fa fa-file-word-o text-primary"></i>',  
		  		        },
		  		        uploadExtraData : function() {
		  		        	return {"goodId": pk_goods_id};
		  		        },
		  		        deleteExtraData	: function() {
		  		        	return {"goodId": pk_goods_id};
		  		        }
		  			});
				 }
			}
		});
	} else {
		// 文件上传初始化
			$("#imageFiles").fileinput({
			    language		: 'zh',							// 中文  
			    uploadUrl		: $.ctx + '/goods/goodsIntroduction/addGoodsPictures',
			    deleteUrl		: $.ctx + '/goods/goodsIntroduction/delPictures',
			    showPreview		: true,              			// 展前预览  
			    showUpload		: false,              			// 不显示上传按钮  
			    showCaption		: false,             			// 不显示文字表述  
			    uploadAsync		: false,                         // 采用同步上传  
			    removeFromPreviewOnError:true,                 	// 当文件不符合规则，就不显示预览  
			    maxFileCount	: 3,							// 最大上传图片数
			    maxFileSize		: 512,                          // 单位为kb，如果为0表示不限制文件大小  
			    browseClass 	: "btn btn-info",
			    allowedFileExtensions: ["jpg", "jpeg", "gif", "png","bmp"],
			    initialPreviewFileType : 'image',
			    initialPreviewAsData: true,
		        previewFileIconSettings: {  
		            'docx': '<i class="fa fa-file-word-o text-primary"></i>',  
		            'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',  
		            'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',  
		            'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',  
		            'zip': '<i class="fa fa-file-archive-o text-muted"></i>',  
		            'sql': '<i class="fa fa-file-word-o text-primary"></i>',  
		        },
		        uploadExtraData : function() {
		        	return {"goodId": pk_goods_id};
		        },
		        deleteExtraData	: function() {
		        	return {"goodId": pk_goods_id};
		        }
			});
	}
//	$("#imageFiles").on('filepredelete', function(event, key, jqXHR, data) {
//		$.confirm({
//            title: '提示！',
//            content: '您确定要删除这张图片吗吗！',
//            autoClose: 'cancel|10000',
//            buttons: {
//            	confirm: {
//                    text: "确定",
//                    btnClass: 'btn-info',
//                    keys: ['enter'],
//                    action: function() {
//                    	return true;
//                    }
//                },
//                cancel: {
//                    text: "取消",
//                    btnClass: 'btn-danger',
//                    keys: ['esc'],
//                    action:function () { return false;}
//                }
//            }
//        });
//	});
};

/**
 * 商品删除处理
 */
goods.goodsIntroduction.main.del = function() {
	var ids = [];
	$.each($(".checked_img"), function(index, item) {
		if ($(item).css("visibility") != "hidden") {
			ids.push($(item).next().find("#goods_id").val());
		}
	});

	if(ids.length > 0) {
		$.confirm({
            title: '提示！',
            content: '您确定要删除商品信息吗！',
            autoClose: 'cancel|10000',
            buttons: {
            	confirm: {
                    text: "确定",
                    btnClass: 'btn-info',
                    keys: ['enter'],
                    action: function() {
                    	$.post(
        					$.ctx + '/goods/goodsIntroduction/del',
        					{
        						goods_id : ids.join(",")
        					},
        					function(result) {
        						if (result.isSuccess && result.rslt_flag == "0") {
        							$.alert({
        							    title: '提示',
        							    content: '删除成功!',
        							    text: "确认"
        							});
        							
        							// 刷新一览部数据
        							goods.goodsIntroduction.main.search();
        						} else {
        							$.alert({
        							    title: '提示',
        							    content: '删除失败!',
        							    text: "确认"
        							});
        						}
        					}, 
        				"json");
                    }
                },
                cancel: {
                    text: "取消",
                    btnClass: 'btn-danger',
                    keys: ['esc'],
                    action:function () {}
                }
            }
        });
	} else {
		$.alert({
		    title: '提示',
		    content: '请先选择一条数据!',
		    buttons: {
		    	confirm: {
		    		text: "确定",
                    btnClass: 'btn-info'
		    	}
		    }
		});
	}
};

/**
 * 清空检索栏
 */
goods.goodsIntroduction.main.clearData = function() {
	$("#goods_type_name").val("");
	$("#goods_name").val("");
}

/**
 * 商品更新处理
 * 
 */
goods.goodsIntroduction.main.save = function() {
	$("#goodsDetailForm").attr('action',$.ctx + '/goods/goodsIntroduction/saveOrUpdate');
	$("#typeId").val($('input:radio[name="goodsTypeRadio"]:checked').val());
	var errMsg = "";
	if (isEmpty($("#goodName").val())) {
		errMsg += "<span style='color:red;'>请输入商品名称！</span><br/>";
	}
	
	if(isEmpty($('input:radio[name="goodsTypeRadio"]:checked').val())) {
		errMsg += "<span style='color:red;'>请输入商品名称！</span><br/>";
	}
	
	var goodPriceJp = $("#goodPriceJp").val();
	if(isEmpty(goodPriceJp)) {
		errMsg += "<span style='color:red;'>请输入商品价格(日元)！</span><br/>";
	} else if (!$.isNumeric(goodPriceJp)) {
		errMsg += "<span style='color:red;'>请输入正确的商品价格(日元)！</span><br/>";
	}
	
	var goodPrice = $("#goodPrice").val();
	if(isEmpty(goodPrice)) {
		errMsg += "<span style='color:red;'>请输入商品价格(人民币)！</span><br/>";
	} else if (!$.isNumeric(goodPrice)) {
		errMsg += "<span style='color:red;'>请输入正确的商品价格(人民币)！</span><br/>";
	}
	
	if(!isEmpty(errMsg)) {
		$.alert({
		    title: '出错提示',
		    content: errMsg,
		    buttons: {
		    	confirm: {
		    		text: "确定",
                    btnClass: 'btn-warning'
		    	}
		    }
		});
		return;
	}

	// 图片上传成功后， 更新数据处理
	var param = $('#goodsDetailForm').serialize();
  	$.ajax({
		type:"POST",
		dataType : "json",
		url : $.ctx + '/goods/goodsIntroduction/saveOrUpdate',
		data : param,
		success : function(data) {
			pk_goods_id = data.data.goodId; 
			$("#imageFiles").fileinput("upload");
			$("#imageFiles").on("filebatchuploadsuccess", function(event, data, previewId, index) {
				$('#goodsDetailModal').modal('hide');
				$.alert({
				    title: '提示',
				    content: '保存成功!',
				    buttons: {
				    	confirm: {
				    		text: "确定",
		                    btnClass: 'btn-info'
				    	}
				    }
				});
				// 刷新一览部数据
				goods.goodsIntroduction.main.search();
			});
			$('#imageFiles').on('filebatchuploaderror', function(event, data, msg) {
				$.alert({
				    title: '提示',
				    content: '图片上传失败!',
				    buttons: {
				    	confirm: {
				    		text: "确定",
		                    btnClass: 'btn-danger'
				    	}
				    }
				});
			});
		}
  	});
}

